package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"shop-bean/constant"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils/contextArgs"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
	"shop-service/business"
)

type TransportController struct {
}

// @Tags 运费模板
// @description: 获取运费模板列表
// @Summary 获取运费模板列表
// @Security ApiKeyAuth
// @function: List
// @Accept  json
// @Produce  json
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport/list [get]
func (c *TransportController) List(ctx *gin.Context) {
	shopId, err := contextArgs.GetSHopId(ctx)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	list, err := business.ServiceImpl().TransportService.Find(ctx, shopId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}
	serializer.SuccessData(ctx, "", &list)
}

// @Tags 运费模板
// @description: 分页
// @Summary 分页
// @Security ApiKeyAuth
// @function: Page
// @Accept  json
// @Produce  json
// @Param current query string false "当前页，默认1"
// @Param size query string false "每页大小，默认10"
// @Param keyword query string false "keyword"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport/page [get]
func (t *TransportController) Page(ctx *gin.Context) {
	form := pagehelper.SearchPageRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	paginator := pagehelper.New().SetOffset(form).SetFilter([]string{"transport_id"}).
		IsPush(form.Keyword != "", queryWrapper.Like("trans_name", form.Keyword)).
		Push(queryWrapper.Eq("shop_id", constant.SHOP_ID)).Paginator()
	pagehelper.New()

	page, err := business.ServiceImpl().TransportService.FindPage(ctx, paginator)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", page)
}

// @Tags 运费模板
// @description: 获取信息
// @Summary 获取信息
// @Security ApiKeyAuth
// @function: Info
// @Accept  json
// @Produce  json
// @Param transportId path int true "运费模板id"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport/info/{transportId} [get]
func (c *TransportController) Info(ctx *gin.Context) {
	transportId, err := contextArgs.GetUriIntPath(ctx, "transportId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var transport model.Transport
	err = variables.GormDB().First(&transport, uint(transportId)).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	transfees, err := business.ServiceImpl().TransportService.FindTransfee(ctx, transport.TransportId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	transfeeFrees, err := business.ServiceImpl().TransportService.FindFransfeeFree(ctx, transport.TransportId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", map[string]interface{}{
		"transport":     transport,
		"transfees":     transfees,
		"transfeeFrees": transfeeFrees,
	})
}

// @Tags 运费模板
// @description: 保存
// @Summary 保存
// @accept application/json
// @Produce application/json
// @Param data body request.TransportRequest true "新增运费模板"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport [post]
func (c *TransportController) Save(ctx *gin.Context) {
	form := request.TransportRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if err := verifyForm(&form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	exist, err := business.ServiceImpl().TransportService.CheckExist(ctx, form.TransName)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicCreateErr)
		return
	} else if exist {
		serializer.Fail(ctx, "模板名称已存在")
		return
	}

	id, err := business.ServiceImpl().TransportService.Create(ctx, &form)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicCreateErr)
		return
	}

	serializer.SuccessData(ctx, "", id)
}

// @Tags 运费模板
// @description: 修改
// @Summary 修改
// @accept application/json
// @Produce application/json
// @Param data body request.TransportRequest true "编辑运费模板"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport [put]
func (c *TransportController) Update(ctx *gin.Context) {
	form := request.TransportRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}
	if form.TransportId == 0 {
		serializer.Fail(ctx, "ID不能为空")
		return
	}

	if err := verifyForm(&form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	id, err := business.ServiceImpl().TransportService.Updates(ctx, &form)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	serializer.SuccessData(ctx, "", id)
}

func verifyForm(form *request.TransportRequest) error {
	// 所有地区 不需要传递地址
	if len(form.Transfees) > 0 {
		if len(form.Transfees[0].CityList) > 0 {
			return errors.New("可配送区域参数不合法")
		}
	}

	// 验证卖家包邮传递的参数
	if form.IsFreeFee == 2 {
		if len(form.Transfees) != 1 {
			return errors.New("可配送区域参数不合法")
		}

		if len(form.Transfees) == 1 {
			if form.Transfees[0].FirstPiece != 1 ||
				form.Transfees[0].FirstFee != 0 ||
				form.Transfees[0].ContinuousPiece != 0 ||
				form.Transfees[0].ContinuousFee != 0 {
				return errors.New("可配送运费参数不合法")
			}
		}

		if len(form.TransfeeFrees) > 0 || form.HasFreeCondition == 2 {
			return errors.New("指定条件包邮项不合法")
		}

		if form.ChargeType != 1 {
			return errors.New("收费方式不正确")
		}
	}

	return nil
}

// @Tags 运费模板
// @description: 删除
// @Summary 删除
// @Security ApiKeyAuth
// @function: Delete
// @Accept  json
// @Produce  json
// @Param transportId path int true "transportId"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/transport/{transportId} [delete]
func (c *TransportController) Delete(ctx *gin.Context) {
	transportId, err := contextArgs.GetUriIntPath(ctx, "transportId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err = business.ServiceImpl().TransportService.DeleteById(ctx, uint(transportId))
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	serializer.Success(ctx, "")
}
